<template>
  <BhTable
      title="用户管理"
      row-key="id"
      v-model:selected-keys="selectedKeys"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :data="dataList as []"
      :columns="columns"
      @refresh="search"
      :loading="loading"
      :pagination="pagination"
      :row-selection="rowSelection"
      :disabled-column-keys="['name']"
  >
    <!--搜索 -->
    <template #top>
      <BhForm  ref="formRef" :columns="queryColumns" :model-value="queryForm"
               :options="options" @search="search" @reset="reset"></BhForm>
    </template>
    <!-- 操作按钮 -->
    <template #toolbar-left>
      <a-space>
        <a-button
            v-permission="['sys:level:add']"
            type="primary"
            @click="emits('openAdd')"
        >
          <template #icon>
            <icon-plus/>
          </template>
          {{ $t('common.create') }}
        </a-button>
        <a-button
            v-permission="['sys:level:delete']"
            type="primary"
            status="danger"
            :disabled="selectedKeys.length === 0"
            @click="deleteSelectRows"
        >
          <template #icon>
            <icon-delete/>
          </template>
          {{ $t('common.delete') }}
        </a-button>
      </a-space>
    </template>
    <!-- 头像 -->
    <template #avatar="{ record }">
      <BhAvatar :url="record.avatar"></BhAvatar>
    </template>
    <template #status="{ record }">
      <!-- 有修改权限 -->
      <a-switch
          v-if="hasPermission('sys:level:status')"
          v-model="record.status"
          type="round"
          :checked-text="TableSwitchStatusText.checkedText"
          :unchecked-text="TableSwitchStatusText.uncheckedText"
          :checked-value="TableSwitchStatus.ENABLED"
          :unchecked-value="TableSwitchStatus.DISABLED"
          :before-change="(s: number) => updateStatus(record.id, s)"
      />
      <a-badge
          v-else
          :status="record.status == TableSwitchStatus.ENABLED ? 'processing' : 'danger'"
          :text="record.status == TableSwitchStatus.DISABLED ? '开启' : '关闭'"
      />
    </template>
    <!-- 操作 -->
    <template #handle="{ record }">
      <!-- 修改 -->
      <a-button
          v-permission="['sys:user:edit']"
          type="text"
          size="mini"
          @click="emits('openUpdate', record)"
      >
        修改
      </a-button>
      <!-- 重置密码 -->
      <a-button
          v-permission="['sys:user:retpassword']"
          type="text"
          size="mini"
          :disabled="record.id === userStore.id"
          @click="emits('openResetPassword', record)"
      >
        重置密码
      </a-button>
      <!-- 分配角色 -->
      <a-button
          v-permission="['sys:user:role']"
          type="text"
          size="mini"
          @click="emits('openGrantRole', record)"
      >
        分配角色
      </a-button>
      <!-- 删除 -->
      <a-button
          v-permission="['sys:user:delete']"
          type="text"
          size="mini"
          status="danger"
          @click="deleteRow(record)"
          :disabled="record.id === userStore.id"
      >
        删除
      </a-button>

    </template>

  </BhTable>

</template>

<script lang="ts" setup>

import {useLoading} from '@/hooks/modules/useLoading';
import {useTable} from '@/hooks/modules/useTable';
import {getUserList,updateUserStatus,batchDeleteUser,deleteUser} from '@/api/system/user';
import {Message} from '@arco-design/web-vue';
import type {UserQueryRequest, UserQueryResponse} from '@/api/system/user';
import {useUserStore} from '@/store';
import usePermission from '@/hooks/permission';
import columns from '../types/table.columns';
import {TableSwitchStatus,TableSwitchStatusText} from '@/types/const';
import { type Columns, BhForm, type Options } from '@/components/BhForm'

const emits = defineEmits([
  'openAdd',
  'openUpdate',
  'openResetPassword',
  'openGrantRole',
]);

const {hasPermission} = usePermission();
const {setLoading} = useLoading();
const userStore = useUserStore();

const options: Options = {
  form: { layout: 'inline' },
  grid: { cols: { xs: 1, sm: 1, md: 2, lg: 3, xl: 3, xxl: 2 } },
  fold: { enable: false, index: 1, defaultCollapsed: true },
}
const queryForm = reactive<UserQueryRequest>({
  username: undefined,
});

const queryColumns: Columns = reactive([
  {
    label: '用户账号',
    field: 'username',
    type: 'input',
    props: {
      placeholder: '请输入用户账号',
    }
  },
])

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete,
  selectedKeys,
  rowSelection
} = useTable((page) => getUserList({...queryForm, ...page}), {
  immediate: true,
});

//重置搜索
const reset = () => {
  queryForm.username = undefined
  search()
}

// 更新后回调
const restartCallback = () => {
  search();
};

defineExpose({
  restartCallback,
});

// 更新状态
const updateStatus = (id: number, status: number) => {
  return updateUserStatus({
    id,
    status,
  }).then(() => {
    Message.success('操作成功');
  });
};
// 批量删除
const deleteSelectRows = async () => {
  if (selectedKeys.value.length <= 0) {
    Message.error('请选择数据');
  }
  try {
    setLoading(true);
    // 调用删除接口
    await batchDeleteUser(selectedKeys.value);
    Message.success(`成功删除 ${selectedKeys.value.length} 条数据`);
    selectedKeys.value = [];
    reset()
  } catch (e) {
    setLoading(false);
  } finally {
    setLoading(false);
  }
};
// 删除当前行
const deleteRow = async (record: UserQueryResponse) => {
  return handleDelete(() => deleteUser(record.id), {
    content: `是否确定删除用户「${record.username}」？`,
    showModal: true,
  })
};
</script>

<style scoped lang="less">

</style>
